<template>
  <div class="review-list-container">
    <el-card class="review-card">
      <template #header>
        <div class="card-header">
          <span>我的评价</span>
          <div class="filter-form">
            <el-select v-model="filterForm.type" placeholder="评价类型" clearable>
              <el-option label="全部评价" value=""></el-option>
              <el-option label="产品评价" value="product"></el-option>
              <el-option label="设计师评价" value="designer"></el-option>
            </el-select>
            <el-select v-model="filterForm.rating" placeholder="评分" clearable>
              <el-option label="全部评分" value=""></el-option>
              <el-option label="5星" value="5"></el-option>
              <el-option label="4星" value="4"></el-option>
              <el-option label="3星" value="3"></el-option>
              <el-option label="2星" value="2"></el-option>
              <el-option label="1星" value="1"></el-option>
            </el-select>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="已评价" name="completed"></el-tab-pane>
        <el-tab-pane label="待评价" name="pending"></el-tab-pane>
      </el-tabs>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
        <el-skeleton style="margin-top: 20px" :rows="3" animated />
      </div>
      
      <!-- 已评价列表 -->
      <div v-else-if="activeTab === 'completed' && reviewList.length > 0" class="review-items">
        <div v-for="review in reviewList" :key="review.id" class="review-item">
          <div class="review-item-header">
            <div class="review-target">
              <el-tag size="small" :type="review.type === 'product' ? 'success' : 'warning'">
                {{ review.type === 'product' ? '产品评价' : '设计师评价' }}
              </el-tag>
              <span class="review-title">{{ review.targetName }}</span>
            </div>
            <div class="review-time">{{ review.createTime }}</div>
          </div>
          
          <div class="review-item-content">
            <div class="review-rating">
              <span>评分：</span>
              <el-rate v-model="review.rating" disabled text-color="#ff9900"></el-rate>
            </div>
            <div class="review-text">{{ review.content }}</div>
            
            <div class="review-images" v-if="review.images && review.images.length > 0">
              <el-image 
                v-for="(image, imgIndex) in review.images" 
                :key="imgIndex"
                :src="image" 
                :preview-src-list="review.images"
                fit="cover"
                class="review-image">
              </el-image>
            </div>
            
            <div class="review-action">
              <el-button type="primary" text @click="editReview(review)">修改</el-button>
              <el-button type="danger" text @click="deleteReview(review)">删除</el-button>
            </div>
          </div>
          
          <div v-if="review.replyContent" class="review-reply">
            <div class="reply-header">商家回复：</div>
            <div class="reply-content">{{ review.replyContent }}</div>
            <div class="reply-time">{{ review.replyTime }}</div>
          </div>
        </div>
        
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>
      
      <!-- 待评价列表 -->
      <div v-else-if="activeTab === 'pending' && pendingList.length > 0" class="pending-items">
        <el-table :data="pendingList" style="width: 100%">
          <el-table-column label="类型" width="120">
            <template #default="scope">
              <el-tag size="small" :type="scope.row.type === 'product' ? 'success' : 'warning'">
                {{ scope.row.type === 'product' ? '产品' : '设计师' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="targetName" label="名称"></el-table-column>
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column prop="completeTime" label="完成时间" width="180"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="goToReview(scope.row)">
                去评价
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            @size-change="handlePendingSizeChange"
            @current-change="handlePendingCurrentChange"
            :current-page="pendingPagination.currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pendingPagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pendingPagination.total">
          </el-pagination>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else class="empty-container">
        <el-empty 
          :description="activeTab === 'completed' ? '暂无评价记录' : '暂无待评价项目'"
          :image-size="200">
        </el-empty>
      </div>
    </el-card>
    
    <!-- 编辑评价对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改评价"
      width="50%">
      <el-form 
        ref="reviewFormRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="100px">
        
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="reviewForm.rating" show-score></el-rate>
        </el-form-item>
        
        <el-form-item label="评价内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="reviewForm.content" 
            :rows="4"
            placeholder="请输入您的评价内容">
          </el-input>
        </el-form-item>
        
        <el-form-item label="评价图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :file-list="reviewImages">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditReview">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getMyReviews, updateReview, deleteReview, getPendingReviewOrders, getPendingReviewDesigners } from '@/api/review'

export default {
  name: 'ReviewList',
  components: {
    Plus
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const activeTab = ref('completed')
    const reviewList = ref([])
    const pendingList = ref([])
    const editDialogVisible = ref(false)
    const reviewFormRef = ref(null)
    const currentReview = ref(null)
    const reviewImages = ref([])
    
    // 筛选表单
    const filterForm = reactive({
      type: '',
      rating: ''
    })
    
    // 分页信息 - 已评价
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 分页信息 - 待评价
    const pendingPagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 评价表单
    const reviewForm = reactive({
      id: '',
      rating: 5,
      content: '',
      images: []
    })
    
    // 评价表单验证规则
    const reviewRules = {
      rating: [
        { required: true, message: '请选择评分', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入评价内容', trigger: 'blur' },
        { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符', trigger: 'blur' }
      ]
    }
    
    // 初始化
    onMounted(() => {
      fetchReviewList()
    })
    
    // 获取评价列表
    const fetchReviewList = async () => {
      loading.value = true
      
      try {
        if (activeTab.value === 'completed') {
          // 获取已完成评价列表
          const params = {
            page: pagination.currentPage,
            pageSize: pagination.pageSize,
            type: filterForm.type,
            rating: filterForm.rating
          }
          
          // 实际项目中应调用API
          // const res = await getMyReviews(params)
          
          // 模拟API响应
          setTimeout(() => {
            const mockResponse = {
              data: {
                total: 23,
                list: generateMockReviews()
              }
            }
            
            reviewList.value = mockResponse.data.list
            pagination.total = mockResponse.data.total
            loading.value = false
          }, 800)
        } else {
          // 获取待评价列表
          await fetchPendingReviews()
        }
      } catch (error) {
        ElMessage.error('获取评价列表失败')
        loading.value = false
      }
    }
    
    // 获取待评价列表
    const fetchPendingReviews = async () => {
      loading.value = true
      
      try {
        // 合并产品和设计师待评价列表
        const productParams = {
          page: pendingPagination.currentPage,
          pageSize: pendingPagination.pageSize
        }
        
        const designerParams = {
          page: pendingPagination.currentPage,
          pageSize: pendingPagination.pageSize
        }
        
        // 实际项目中应调用API
        // const productRes = await getPendingReviewOrders(productParams)
        // const designerRes = await getPendingReviewDesigners(designerParams)
        
        // 模拟API响应
        setTimeout(() => {
          const mockResponse = {
            data: {
              total: 8,
              list: generateMockPendingReviews()
            }
          }
          
          pendingList.value = mockResponse.data.list
          pendingPagination.total = mockResponse.data.total
          loading.value = false
        }, 800)
      } catch (error) {
        ElMessage.error('获取待评价列表失败')
        loading.value = false
      }
    }
    
    // 生成模拟评价数据
    const generateMockReviews = () => {
      const reviews = []
      for (let i = 1; i <= pagination.pageSize; i++) {
        const id = (pagination.currentPage - 1) * pagination.pageSize + i
        const type = Math.random() > 0.5 ? 'product' : 'designer'
        
        reviews.push({
          id,
          type,
          targetId: id,
          targetName: type === 'product' ? `定制产品${id}` : `设计师${id}`,
          rating: Math.floor(Math.random() * 2) + 4, // 4-5星
          content: '非常满意这次的定制服务，产品质量很好，做工精细，完全符合我的期望。设计师很专业，对我的需求理解到位。',
          images: Math.random() > 0.5 ? [
            'https://via.placeholder.com/150?text=Review1',
            'https://via.placeholder.com/150?text=Review2'
          ] : [],
          createTime: '2023-05-15 14:32:10',
          replyContent: Math.random() > 0.3 ? '感谢您的评价，我们将继续努力提供更好的服务！' : '',
          replyTime: Math.random() > 0.3 ? '2023-05-16 10:25:30' : ''
        })
      }
      return reviews
    }
    
    // 生成模拟待评价数据
    const generateMockPendingReviews = () => {
      const reviews = []
      for (let i = 1; i <= 8; i++) {
        const type = i % 2 === 0 ? 'product' : 'designer'
        
        reviews.push({
          id: i,
          type,
          targetId: i,
          targetName: type === 'product' ? `定制西装${i}` : `设计师${i}`,
          orderNo: `DD${new Date().getFullYear()}${String(i).padStart(6, '0')}`,
          completeTime: '2023-06-20 15:30:45'
        })
      }
      return reviews
    }
    
    // 处理评价图片上传
    const handleImageChange = (file, fileList) => {
      reviewImages.value = fileList
      
      // 将图片转为URL保存（实际项目中应该上传到服务器）
      const imageUrls = []
      fileList.forEach(item => {
        if (item.url) {
          imageUrls.push(item.url)
        } else if (item.raw) {
          const reader = new FileReader()
          reader.readAsDataURL(item.raw)
          reader.onload = () => {
            imageUrls.push(reader.result)
          }
        }
      })
      
      reviewForm.images = imageUrls
    }
    
    // 编辑评价
    const editReview = (review) => {
      currentReview.value = review
      reviewForm.id = review.id
      reviewForm.rating = review.rating
      reviewForm.content = review.content
      reviewForm.images = review.images || []
      
      // 转换图片格式为上传组件需要的格式
      reviewImages.value = (review.images || []).map((url, index) => ({
        name: `image-${index}`,
        url
      }))
      
      editDialogVisible.value = true
    }
    
    // 提交编辑评价
    const submitEditReview = async () => {
      const valid = await reviewFormRef.value.validate().catch(() => false)
      if (!valid) return
      
      try {
        // 调用API更新评价
        // 实际项目中应调用API
        // await updateReview(reviewForm.id, {
        //   rating: reviewForm.rating,
        //   content: reviewForm.content,
        //   images: reviewForm.images
        // })
        
        // 模拟API调用
        setTimeout(() => {
          // 更新本地数据
          const index = reviewList.value.findIndex(item => item.id === reviewForm.id)
          if (index !== -1) {
            reviewList.value[index] = {
              ...reviewList.value[index],
              rating: reviewForm.rating,
              content: reviewForm.content,
              images: reviewForm.images
            }
          }
          
          ElMessage.success('评价修改成功')
          editDialogVisible.value = false
        }, 500)
      } catch (error) {
        ElMessage.error('修改评价失败')
      }
    }
    
    // 删除评价
    const deleteReview = (review) => {
      ElMessageBox.confirm('确定要删除该评价吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用API删除评价
          // 实际项目中应调用API
          // await deleteReview(review.id)
          
          // 模拟API调用
          setTimeout(() => {
            // 更新本地数据
            reviewList.value = reviewList.value.filter(item => item.id !== review.id)
            
            ElMessage.success('评价删除成功')
          }, 500)
        } catch (error) {
          ElMessage.error('删除评价失败')
        }
      }).catch(() => {})
    }
    
    // 跳转到评价页面
    const goToReview = (item) => {
      if (item.type === 'product') {
        router.push(`/review/product/${item.targetId}`)
      } else {
        router.push(`/review/designer/${item.targetId}`)
      }
    }
    
    // 处理标签页切换
    const handleTabChange = (tab) => {
      if (tab === 'pending') {
        fetchPendingReviews()
      } else {
        fetchReviewList()
      }
    }
    
    // 处理查询
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchReviewList()
    }
    
    // 处理每页条数变化 - 已评价
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      fetchReviewList()
    }
    
    // 处理页码变化 - 已评价
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchReviewList()
    }
    
    // 处理每页条数变化 - 待评价
    const handlePendingSizeChange = (val) => {
      pendingPagination.pageSize = val
      fetchPendingReviews()
    }
    
    // 处理页码变化 - 待评价
    const handlePendingCurrentChange = (val) => {
      pendingPagination.currentPage = val
      fetchPendingReviews()
    }
    
    return {
      loading,
      activeTab,
      reviewList,
      pendingList,
      filterForm,
      pagination,
      pendingPagination,
      editDialogVisible,
      reviewFormRef,
      reviewForm,
      reviewRules,
      reviewImages,
      handleTabChange,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handlePendingSizeChange,
      handlePendingCurrentChange,
      editReview,
      deleteReview,
      goToReview,
      handleImageChange,
      submitEditReview
    }
  }
}
</script>

<style scoped>
.review-list-container {
  padding: 20px;
}

.review-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-form {
  display: flex;
  gap: 10px;
}

.loading-container,
.empty-container {
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.review-items {
  margin-top: 20px;
}

.review-item {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.review-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.review-target {
  display: flex;
  align-items: center;
}

.review-title {
  margin-left: 10px;
  font-weight: bold;
}

.review-time {
  color: #909399;
  font-size: 14px;
}

.review-item-content {
  margin-bottom: 10px;
}

.review-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.review-text {
  margin-bottom: 10px;
  line-height: 1.6;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.review-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}

.review-action {
  display: flex;
  justify-content: flex-end;
}

.review-reply {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}

.reply-header {
  font-weight: bold;
  margin-bottom: 5px;
}

.reply-content {
  margin-bottom: 5px;
  line-height: 1.6;
}

.reply-time {
  color: #909399;
  font-size: 12px;
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-form {
    margin-top: 10px;
    width: 100%;
  }
  
  .review-item-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .review-time {
    margin-top: 5px;
  }
}
</style> 